<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Expert;
use App\Models\Teache;
class ExpertController extends Controller
{
    //专家文章板块
    public function expert_add(Request $request){
        if($request->isMethod('post')){
            $data = $request->all();
            //截取文章前50个文字
            $tell = strip_tags($data['content']);
            $data['tell'] = mb_substr($tell,0,50,'utf-8');
            //图片上传
            $file = $request->file('img')->store(date('Y-m-d'));
            $data['img'] = $file;
            //添加数据
            $expert = new Expert();
            $list =$expert->create($data);
            if($list != false && $list != null){
                session()->flash('success','发布成功');
                return redirect('admin/expert/expert_add');
            }else{
                session()->flash('success','发布失败');
                return redirect('admin/expert/expert_add');
            }
        }else{
            $teach = new Teache();
            $t_data = $teach->get();
            return view('Admin/expert/expert_add',['t_data'=>$t_data]);
        }
    }
    //列表板块
    public function expert_list(Expert $expert){
        $data = $expert->get();
        return view('Admin/expert/expert_list',['data'=>$data]);
    }
    //修改
    public function expert_upd(Expert $expert,$id){
        $data = $expert->where('id',$id)->get();
        return view('Admin/expert/expert_upd',['data'=>$data]);
    }
    //提交修改
    public function expert_update(Request $request,Expert $expert){
        $data = $request->except('_token');
        $where = ['id' => $data['id']];
        if (!empty($data['content'])){
            $tell = strip_tags($data['content']);
            $re['tell'] = mb_substr($tell,0,50,'utf-8');
            $re['content'] = $data['content'];
        }
        if(!is_null($request->file('img'))){
            $re['img'] = $request->file('img')->store(date('Y-m-d'));
        }
        $re['title'] = $data['title'];
        $re['recomm'] = $data['recomm'];
        $re['teach'] = $data['teach'];
        $result = $expert->where($where)->update($re);
        if($result != false){
            session()->flash('success','修改成功');
            return redirect()->back();
        }else{
            session()->flash('success','修改失败');
            return redirect()->back();
        }
    }
    //删除
    public function delete($id){
        $expert = new Expert();
        $list = $expert->where('id',$id)->delete();
        return redirect()->back();
    }
}
